package com.tougutips.like.mq;

import com.rabbitmq.client.Channel;
import com.tougutips.common.like.vo.LikeVO;
import com.tougutips.like.enums.LikeEnums;
import com.tougutips.like.enums.LikeSetNameEnum;
import com.tougutips.like.dto.MessageDto;
import org.apache.ibatis.javassist.Loader;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

/**
 * @author 张治怡
 * @version 1.0
 * @description 消息处理
 * @dateTime 2022/7/22 11:00
 */

@Component
public class UserLikeReceiver {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    private String setName;

    @RabbitListener(queues = "likeQueue")
    public void LikeReceiver(Channel channel, Message message, LikeVO userlike) {
        //手动确认
        try {
            setName = LikeSetNameEnum.getTypeName(userlike.getLikeType());
            redisTemplate.opsForSet().add(setName, userlike.getLikeId()+"");
            HashMap<Object, Object> map = new HashMap<>();
            long likeTime = System.currentTimeMillis();
            map.put(userlike.getUserId()+"", likeTime);
            redisTemplate.opsForHash().putAll(setName + ":" + userlike.getLikeId(), map);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            //发送给通知队列,进行消息转发
            MessageDto messageDto = new MessageDto();
            BeanUtils.copyProperties(userlike,messageDto);
            messageDto.setLikeTime(new Date(likeTime));
            rabbitTemplate.convertAndSend(LikeEnums.EXCHANGE_NAME.getValue(),LikeEnums.MESSAGE_QUEUE_ROUTING_KEY.getValue(),messageDto);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
